package com.muy.redis.common.tree.actions;

import com.google.common.collect.Lists;
import com.intellij.icons.AllIcons;
import com.muy.redis.common.dialog.MrRedisConfirmDialog;
import com.muy.redis.common.tree.MTTreeCell;
import com.muy.redis.common.tree.TreePanelMark;
import com.muy.redis.utils.MrRedisConnectionUtils;
import com.muy.redis.view.component.MrRedisEditorJpanelLeft;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisEditorShowDb;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisKey;
import org.apache.commons.lang3.tuple.Pair;
import redis.clients.jedis.Jedis;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.List;

/**
 * @Author jiyanghuang
 * @Date 2022/8/4 21:10
 */
public class MrRedisDeleteKeyAction extends AbstractMTTreeCellSelectTreeAction {

    private TreePanelMark treePanelMark;

    public MrRedisDeleteKeyAction(TreePanelMark treePanelMark) {
        super("Delete", "Delete", AllIcons.General.Remove, treePanelMark);
        this.treePanelMark = treePanelMark;
    }

    @Override
    public void handleSelectTree(DefaultMutableTreeNode mutableTreeNode, MTTreeCell mtTreeCell) {
        MrRedisEditorJpanelLeft mrRedisEditorJpanelLeft = (MrRedisEditorJpanelLeft)treePanelMark;
        if(mtTreeCell instanceof MTTreeCellMrRedisKey){
            MTTreeCellMrRedisKey mtTreeCellMrRedisKey = (MTTreeCellMrRedisKey)mtTreeCell;
            new MrRedisConfirmDialog("Are you sure delete key ? ", "Delete Redis Key", mrRedisEditorJpanelLeft.getProject(), (form) -> {
                try(Jedis jedis = MrRedisConnectionUtils.findRedisPoolManager(mrRedisEditorJpanelLeft.getMrRedisConnectionParam()).getJedis(mrRedisEditorJpanelLeft.getMrRedisDb().getIndex())){
                    if(null != jedis){
                        List<String> keys = Lists.newArrayList(mtTreeCellMrRedisKey.getRedisKey());
                        jedis.del(keys.toArray(new String[]{}));
                        mrRedisEditorJpanelLeft.renderKeyTree();
                        mtTreeCellMrRedisKey.removeCurrent(mrRedisEditorJpanelLeft.jTree(), mutableTreeNode);
                        mrRedisEditorJpanelLeft.getTabContentRightShow().updatePanelBlank();
                    }
                }
                return Pair.of(true, null);
            }).ofDialogShow();
        }else if(mtTreeCell instanceof MTTreeCellMrRedisEditorShowDb){
//            new MrRedisConfirmDialog("Are you sure delete key ? ", "Delete Redis Key", mrRedisEditorJpanelLeft.getProject(), (form) -> {
//                try(Jedis jedis = MrRedisConnectionUtils.findRedisPoolManager(mrRedisEditorJpanelLeft.getMrRedisConnectionParam()).getJedis(mrRedisEditorJpanelLeft.getMrRedisDb().getIndex())){
//                    if(null != jedis){
//
//                    }
//                }
//                return Pair.of(true, null);
//            }).ofDialogShow();
        }
    }
}
